/**
 * @author xuda-21609
 * @date 2020/2/10
 * @Description: 设备api
 */

import {Toast} from "vant";

/**
 * 获取图片
 * @param next
 */
function getImage(next, options) {
    if (!navigator.camera) return alert('相机功能调用有误')
    navigator.camera.getPicture(onSuccess, onFail, options || {
        quality: 50,
    })

    function onSuccess(imageURI) {
        next(imageURI)
    }

    function onFail(message) {
        console.log('Failed because: ' + message);
        Toast('获取照片失败！')
    }
}

/**
 * 获取定位
 * @param val
 * @param next
 * @param err
 */
function getPosition(next) {
    if (!navigator.geolocation) return alert('该平台暂不支持获取位置功能！')
    let onSuccess = function (position) {
        next(position)
    }

    let onError = function (error) {
        console.log(error)
        alert('code: ' + error.code + '\n' +
            'message: ' + error.message + '\n');
    }

    navigator.geolocation.getCurrentPosition(onSuccess, onError, {
        maximumAge: 300000,
        timeout: 10000,
        enableHighAccuracy: true
    })
}

/**
 * 设备准备就绪
 * @param next
 */
function deviceReady(next) {
    document.addEventListener("deviceready", onReady, false);

    function onReady(res) {
        next(res)
    }
}

/**
 * 获取设备电池状态
 * @param next
 */
function batteryStatus(next) {
    window.addEventListener("batterystatus", onBatteryStatus, false);

    function onBatteryStatus(status) {
        next(status)
        console.log("Level: " + status.level + " isPlugged: " + status.isPlugged);
    }
}

/**
 * 设备原生弹出提示框
 * @param message
 * @param title
 * @param buttonName
 * @param next
 */
function alert(message, title = '标题', buttonName = '好', next) {
    if (!navigator.notification) return Toast('设备暂不支持该功能')

    function cb() {

    }
    navigator.notification.alert(message, next || cb, title, buttonName)
}

/**
 * 设备原生确认框
 * @param message
 * @param title
 * @param buttonName
 * @param next
 * @returns {VanToast}
 */
function confirm(message, title, buttonName, next) {
    if (!navigator.notification) return Toast('设备暂不支持该功能')
    navigator.notification.alert(message, next || alertCallback, title, buttonName);

    function alertCallback(res) {
        console.log(res)
    }
}

export default {
    getImage,
    getPosition,
    deviceReady,
    batteryStatus,
    alert,
    confirm
}
